# coding:utf-8
from django.db import models
import uuid
from me.file_utils import *
from me.netease_music import music_mp3_url


def music_upload_to(instance, filename):
    return 'material/music/%s%s' % (uuid.uuid1(), file_extension(filename))


class MusicGroup(models.Model):
    """
    音乐分组
    """
    name = models.CharField(max_length=20)

    class Meta:
        verbose_name = u'音乐分组'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Music(models.Model):
    """
    音乐素材
    """
    name = models.CharField(max_length=20)
    group = models.ForeignKey(MusicGroup, on_delete=False)
    url = models.URLField('音乐地址', null=True, blank=True)
    sources = (
        ('netease', '网易云音乐',),
        ('local', '本地上传',),
    )
    source = models.CharField('音乐来源', choices=sources, max_length=10, default='local')
    music = models.FileField(verbose_name="音乐文件", upload_to=music_upload_to, max_length=400, null=True, blank=True)
    netease_music_id = models.IntegerField("网易云音乐ID", default=0)
    disabled = models.BooleanField('禁用', default=False)

    class Meta:
        verbose_name = u'音乐素材'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.source == 'netease':
            # 抓取网易音乐源
            url = music_mp3_url(self.netease_music_id)
            self.url = url
        super(Music, self).save(force_insert, force_update, using, update_fields)